<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';

// 状态变量
const authCode = ref('');
const accessToken = ref('');
const userInfo = ref<any>(null);
const loading = ref(false);
const error = ref('');
const step = ref(1); // 1: 初始化, 2: 获取令牌, 3: 获取用户信息, 4: 完成

const route = useRoute();
const router = useRouter();

// 客户端信息
const clientId = '1001'; // OAuth2 客户端ID
const clientSecret = '123456'; // OAuth2 客户端密钥
const redirectUri = window.location.origin + '/oauth/callback';

// 获取授权码
onMounted(async () => {
  // 从URL中获取授权码
  const code = route.query.code as string;
  const state = route.query.state as string;
  
  console.log('授权回调页面加载，参数：', { code, state });
  
  if (!code) {
    error.value = '未收到授权码，授权失败';
    return;
  }
  
  authCode.value = code;
  step.value = 2;
  
  // 使用授权码获取访问令牌
  try {
    loading.value = true;
    await getAccessToken(code);
    step.value = 3;
    
    // 使用访问令牌获取用户信息
    await getUserInfo();
    step.value = 4;
  } catch (err: any) {
    console.error('授权流程出错：', err);
    error.value = err.message || '授权过程中发生错误';
  } finally {
    loading.value = false;
  }
});

// 使用授权码获取访问令牌
async function getAccessToken(code: string) {
  const tokenEndpoint = '/oauth2/token';
  
  // 准备表单数据
  const formData = new FormData();
  formData.append('grant_type', 'authorization_code');
  formData.append('code', code);
  formData.append('client_id', clientId);
  formData.append('client_secret', clientSecret);
  formData.append('redirect_uri', redirectUri);
  
  try {
    console.log('尝试获取访问令牌...');
    
    const response = await fetch(tokenEndpoint, {
      method: 'POST',
      body: formData
    });
    
    const data = await response.json();
    console.log('令牌响应：', data);
    
    if (data.code !== 200 || !data.data || !data.data.access_token) {
      throw new Error(data.message || '获取访问令牌失败');
    }
    
    // 保存访问令牌
    accessToken.value = data.data.access_token;
    console.log('访问令牌获取成功:', accessToken.value);
    
    return data.data;
  } catch (err) {
    console.error('获取访问令牌失败：', err);
    throw new Error('获取访问令牌失败');
  }
}

// 使用访问令牌获取用户信息
async function getUserInfo() {
  const userinfoEndpoint = `/oauth2/userinfo?access_token=${accessToken.value}`;
  
  try {
    console.log('尝试获取用户信息...');
    
    const response = await fetch(userinfoEndpoint);
    const data = await response.json();
    console.log('用户信息响应：', data);
    
    if (data.code !== 200 || !data.data) {
      throw new Error(data.message || '获取用户信息失败');
    }
    
    // 保存用户信息
    userInfo.value = data.data;
    console.log('用户信息获取成功:', userInfo.value);
    
    return data.data;
  } catch (err) {
    console.error('获取用户信息失败：', err);
    throw new Error('获取用户信息失败');
  }
}

// 返回首页
function goHome() {
  router.push('/');
}
</script>

<template>
  <div class="oauth-callback">
    <div class="container">
      <h1>应用授权回调页面</h1>
      
      <!-- 加载中 -->
      <div v-if="loading" class="loading">
        <div class="loader"></div>
        <p>处理授权请求中...</p>
      </div>
      
      <!-- 错误信息 -->
      <div v-if="error" class="error-container">
        <h2>授权失败</h2>
        <p class="error">{{ error }}</p>
        <button @click="goHome" class="btn">返回首页</button>
      </div>
      
      <!-- 授权成功 -->
      <div v-if="!loading && !error && step === 4" class="success-container">
        <div class="success-icon">✓</div>
        <h2>授权成功</h2>
        
        <div class="step" :class="{ active: step >= 2 }">
          <div class="step-icon">1</div>
          <div class="step-content">
            <h3>获取授权码</h3>
            <p class="code-block">{{ authCode }}</p>
          </div>
        </div>
        
        <div class="step" :class="{ active: step >= 3 }">
          <div class="step-icon">2</div>
          <div class="step-content">
            <h3>获取访问令牌</h3>
            <p class="code-block">{{ accessToken }}</p>
          </div>
        </div>
        
        <div class="step" :class="{ active: step >= 4 }">
          <div class="step-icon">3</div>
          <div class="step-content">
            <h3>获取用户信息</h3>
            <div class="user-info" v-if="userInfo">
              <div class="user-avatar">
                <img :src="userInfo.avatar || 'https://via.placeholder.com/100'" alt="用户头像" />
              </div>
              <div class="user-details">
                <p><strong>用户名：</strong> {{ userInfo.username }}</p>
                <p><strong>昵称：</strong> {{ userInfo.nickname }}</p>
                <p><strong>部门：</strong> {{ userInfo.departmentName }}</p>
                <p><strong>角色：</strong> {{ userInfo.roles?.join(', ') }}</p>
              </div>
            </div>
          </div>
        </div>
        
        <button @click="goHome" class="btn">返回首页</button>
      </div>
    </div>
  </div>
</template>

<style scoped>
.oauth-callback {
  min-height: 100vh;
  background-color: #f5f8fa;
  display: flex;
  justify-content: center;
  align-items: center;
  font-family: 'Arial', sans-serif;
  color: #333;
  padding: 20px;
}

.container {
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
  padding: 40px;
  max-width: 700px;
  width: 100%;
}

h1 {
  color: #2c3e50;
  text-align: center;
  margin-bottom: 40px;
  font-size: 28px;
}

h2 {
  color: #2c3e50;
  margin-bottom: 20px;
  text-align: center;
}

.loading {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  min-height: 200px;
}

.loader {
  border: 5px solid #f3f3f3;
  border-top: 5px solid #3498db;
  border-radius: 50%;
  width: 50px;
  height: 50px;
  animation: spin 2s linear infinite;
  margin-bottom: 20px;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.error-container {
  text-align: center;
  padding: 30px;
}

.error {
  color: #e74c3c;
  margin-bottom: 20px;
  padding: 10px;
  background-color: #fdecea;
  border-radius: 4px;
}

.success-container {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.success-icon {
  font-size: 48px;
  color: #2ecc71;
  background-color: rgba(46, 204, 113, 0.1);
  border-radius: 50%;
  width: 80px;
  height: 80px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 20px;
}

.step {
  display: flex;
  width: 100%;
  margin-bottom: 20px;
  padding: 15px;
  border: 1px solid #e6e6e6;
  border-radius: 6px;
  opacity: 0.6;
  transition: all 0.3s ease;
}

.step.active {
  opacity: 1;
  border-left: 4px solid #3498db;
  background-color: #f8f9fa;
}

.step-icon {
  background-color: #3498db;
  color: white;
  width: 30px;
  height: 30px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 15px;
  flex-shrink: 0;
}

.step-content {
  flex-grow: 1;
}

.step h3 {
  margin-top: 0;
  margin-bottom: 10px;
  color: #2c3e50;
}

.code-block {
  background-color: #f6f8fa;
  padding: 8px 12px;
  border-radius: 4px;
  font-family: monospace;
  overflow-wrap: break-word;
  word-break: break-all;
  max-width: 100%;
  overflow-x: auto;
  font-size: 14px;
  border: 1px solid #e6e6e6;
  color: #24292e;
}

.user-info {
  display: flex;
  padding: 15px;
  background-color: #f8f9fa;
  border-radius: 6px;
  border: 1px solid #e6e6e6;
}

.user-avatar {
  margin-right: 20px;
}

.user-avatar img {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  object-fit: cover;
  border: 3px solid white;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
}

.user-details {
  flex-grow: 1;
}

.user-details p {
  margin: 8px 0;
}

.btn {
  background-color: #3498db;
  color: white;
  border: none;
  padding: 12px 24px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 16px;
  margin-top: 20px;
  transition: background-color 0.3s ease;
}

.btn:hover {
  background-color: #2980b9;
}
</style> 